import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {FormValidatorService, GreatModalService} from "great-ngform";
import {ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.less']
})
export class FormComponent implements OnInit {

  form: FormGroup;

  constructor(
    private fb: FormBuilder,
    private formValidatorService: FormValidatorService,
    private greatModalService: GreatModalService
  ) {
  }

  ngOnInit() {
    this.form = this.fb.group({
      chinese: new FormControl(null, [
        this.formValidatorService.chinese({maxLength:10})
      ]),
      alphanumeric: new FormControl(null, [
        this.formValidatorService.alphanumeric({
          length:10
        })
      ]),
      identityCard: new FormControl(null, [
        this.formValidatorService.identityCard()
      ]),
      email: new FormControl(null, [
        this.formValidatorService.email()
      ]),
    });
  }

  submitForm(){
    if(this.form.valid){

    }else{
      this.formValidatorService.checkForm(this.form);
    }
  }

  canDeactivate(
    component?: any,
    currentRoute?: ActivatedRouteSnapshot,
    currentState?: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean> | boolean {
    if(this.form.dirty){
      return this.greatModalService.openDialog(
        (save) => {
          const flag = Math.random() * 10 > 4;
          save(flag);
        },
        (cancle) => {
          cancle();
        });
    }
    return true;
  }

}
